﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Paros.BLL;
using Paros.Domain;
namespace Paros.Win
{
    public partial class CategoryControl : UserControl
    {
        CategoryMgr categoryMgr;
        TreeNode rootNode;
        public CategoryControl()
        {
            InitializeComponent();
            categoryMgr = new CategoryMgr();
        }
 

        private void CategoryControl_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void LoadData()
        {
            tvCategory.Nodes.Clear();
            DataTable table = categoryMgr.GetAllCategories();
            foreach (DataRow row in table.Rows)
            {
                if (row.IsNull("Parent"))
                {
                    TreeNode parentNode = PopulateNode(row);
                    PopulateChildrenNode(row, parentNode);
                }

            }
            rootNode = tvCategory.Nodes[0];
            tvCategory.SelectedNode = rootNode;
            rootNode.ExpandAll();
        }

        private TreeNode PopulateNode(DataRow row)
        {
            CategoryItem item = categoryMgr.GetItem(row);
            TreeNode node = new TreeNode();
            node.Text = item.CategoryName;
            node.Tag = item;
            tvCategory.Nodes.Add(node);
            return node;
        }

        private void PopulateChildrenNode(DataRow parentRow, TreeNode parentNode)
        {
            foreach (DataRow row in parentRow.GetChildRows("parent-child"))
            {
                TreeNode node = new TreeNode();
                CategoryItem item = categoryMgr.GetItem(row);
                node.Text = item.CategoryName;
                node.Tag = item;
                parentNode.Nodes.Add(node);
                PopulateChildrenNode(row, node);
            }
        }

    }
}
